package servlet;

import dao.UserDao;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhangYufei
 * Date: 2021-07-22
 * Time: 15:30
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //0. 如果不做任何限定，服务器端读取 Parameter 的时候默认编码方式和解码方式并不是按照utf-8的规则
        req.setCharacterEncoding("utf-8");
        //1. 先读取用户提交的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String passwordAgain = req.getParameter("passwordAgain");
        if(username == null || "".equals(username) || password == null || "".equals(password)
                || passwordAgain == null || "".equals(passwordAgain)){
            resp.sendError(404,"用户名或者密码不能为空");
            /*resp.setStatus(404);
            resp.sendRedirect("register.html");*/
            return;
        }
        if(!password.equals(passwordAgain)){
            resp.sendError(404,"两次密码不一致");
            return;
        }

        //2. 在数据库中查找是否存在该用户，如果存在返回该用户已被注册，如果不存在则将该用户名和密码添加至数据库中
        UserDao userDao = new UserDao();
        User existUser = userDao.selectByName(username);
        if(existUser != null){
            resp.sendError(404,"注册失败，该用户已经被注册");
            /*resp.setStatus(404);
            resp.sendRedirect("register.html");*/
            return;
        }

        //3. 此时说明用户不存在，构造 User 对象，将该对象添加至数据库中
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        userDao.insert(newUser);

        //4. 返回结果
        resp.setContentType("text/html;charset=utf8");
        resp.setStatus(200);
        //resp.getWriter().write("<h3>注册成功</h3>");
        resp.sendRedirect("blogList");
    }
}
